package com.haidechizi.leetcode;

import java.awt.*;

/**
 * @author: wangdejun
 * @create: 2020-04-07 10:24
 **/
public class _25_k链表翻转 {

    public ListNode reverseKGroup(ListNode head, int k) {

        // 定义头节点
        ListNode newHead = new ListNode(0);
        newHead.next = head;

        ListNode pre = newHead;
        ListNode end = newHead;
        while (end.next != null) {
            for (int i = 0; i < k && end.next != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode start = pre.next;
            ListNode next = end.next;

            // 断开链表
            end.next = null;
            pre.next = revert(start);
            start.next = next;

            pre = start;

            end = pre;
        }
        return newHead.next;

    }

    private ListNode revert(ListNode start) {
        ListNode head = new ListNode(1);
        while (start != null) {
            ListNode next = head.next;
            head.next = start;
            ListNode temp = start.next;
            start.next = next;
            start = temp;
        }
        return head.next;
    }
}
